#include <stdexcept>
#include "card.h"
#include "gamecontroller.h"
#include "gamedatamodel.h"

using namespace std;

GameController::GameController(GameDataModel * gameData, QObject *parent) :
  QObject(parent),
  m_gameData(gameData)
{
	if(!gameData)
		throw new invalid_argument("gameData should be not null");
	
	// Сэкономлю время, сразу зарезервировав нобходимое количество памяти.
	m_openedCards.reserve(2);
}

void GameController::openCard(int i){
	Card * c = m_gameData->cards()[i];
	if(c->isOpen() || c->isDelete())
		return;
	
	if(m_openedCards.size() >= 2){
		m_openedCards[0]->setState(CardStates::Closed);
		m_openedCards.removeAt(0);
	}
	c->setState(CardStates::Opened);
	m_openedCards<<c;
	
	if(m_openedCards.size() > 1 && openedCardsIsEquals()){
		foreach (Card* i, m_openedCards)
			i->setState(CardStates::Deleted);
		m_openedCards.clear();
	}
}

bool GameController::openedCardsIsEquals()
{
	for(int i = 1; i < m_openedCards.size(); ++i){
		if(m_openedCards.at(i)->symbol() != m_openedCards.at(0)->symbol())
			return false;
	}
	return true;
}
